﻿using Max.PH5_2004A.Shopping.Domain;
using Max.PH5_2004A.Shopping.DAL;
using Max.PH5_2004A.Shopping.IRespository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Max.PH5_2004A.Shopping.DTO.Goods;

namespace Max.PH5_2004A.Shopping.Respository
{
    public class GoodsRespository : CRUDRespository<GoodsModel>,
        IGoodsRespository
    {
        MaxPH52004AShoppingDbContext _context;
        public GoodsRespository(MaxPH52004AShoppingDbContext context) : base(context)
        {
            _context = context;
        }

        public int AddGoodsAndImg(GoodsAndImgInputDto dto)
        {
            var t = _context.Database.BeginTransaction();
            try
            {
                #region 业务处理

                GoodsModel goods = new GoodsModel
                {
                    Name = dto.Name,
                    Price = dto.Price
                };
                _context.Goods.Add(goods); //插入商品信息

                //一个商品对应多个图片，所以会有多个商品图片对象
                var list = dto.ImgPaths; //这是获取前台传过来的多个图片

                var imgs = new List<GoodsImgModel>();

                foreach (var path in list)
                {
                    var _img = new GoodsImgModel();
                    _img.GoodsId = goods.Id;
                    _img.ImgPath = path;
                    imgs.Add(_img);
                }

                _context.GoodsImgs.AddRange(imgs);
                _context.SaveChanges();
                #endregion

                t.Commit();  //事务提交
                return 1;
            }
            catch (Exception)
            {
                t.Rollback(); //事务回滚
                return -1;
            }
        }
    }
}
